import React, { useContext, useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
let FormContext = React.createContext()
let ItemContext = React.createContext()
function Form(props) {
  let { initialValues, onFinish, children } = props;
  return <div className='formBox'>
    <FormContext.Provider value={{ obj: initialValues, onFinish }}>
      {children}
    </FormContext.Provider>
  </div>
}
function Item(props) {
  let { label, name, children } = props;
  return <div className="itemBox">
    <ItemContext.Provider value={name}>
      {label ? label + ':' : ''}{children}
    </ItemContext.Provider>
  </div>
}
Form.Item = Item
function Input() {
  let form = useContext(FormContext)
  let item = useContext(ItemContext)
  let inp = useRef()
  useEffect(() => {
    inp.current.value = form.obj[item]
  }, [])
  return <input ref={inp} onChange={e => form.obj[item] = e.target.value} />
  // console.log(form.obj[item], item)
  // let [n, setN] = useState(0)
  // return <input value={form.obj[item]} onChange={e => {
  //   form.obj[item] = e.target.value
  //   setN(++n)
  // }} />
}
function Button(props) {
  let { children } = props;
  let form = useContext(FormContext)
  return <button onClick={e => { form.onFinish(form.obj) }}>{children}</button>
}


class App extends React.Component {

  onFinish = (values) => {
    console.log(values)
  }
  render() {
    return <div className=''>
      <Form
        initialValues={{
          username: '珠峰',
          password: 13
        }}
        onFinish={this.onFinish}

      >
        <Form.Item
          label="Username"
          name="username"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
        >
          <Input />
        </Form.Item>
        <Form.Item>
          <Button>Submit</Button>
        </Form.Item>
      </Form>
    </div >;
  }
}

ReactDOM.render(<App />, document.getElementById('root'))